<?php
/**
 * Jcrop image cropping plugin for jQuery
 */
header("Content-Type: text/json; charset=utf-8");
require_once("../../core/cfg.php");
require_once("../../core/functions.php");

function rotateImage($file, $direction = 'right', $q = 100)
{	
	$arr_direction = array(
		'left'  => 270,
		'right' => 90,
		'180'   => 180
	);
	$size = getimagesize($file);
	$f = imagecreatetruecolor($size[0], $size[1]);
	$s = imagecreatefromjpeg($file);
	imagecopy($f, $s, 0, 0, 0, 0, $size[0], $size[1]);		
	$f = imagerotate($f, (array_key_exists($direction, $arr_direction) ? $arr_direction[$direction] : $arr_direction['right']), 0);
	imagejpeg($f, $file, $q);
	imagedestroy($f);
	return true;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
	$ImageOriginal  = ROOT_DIR.DIRSEP.$_POST['i_origin'];
	$ImageTrumbnail = ROOT_DIR.DIRSEP.$_POST['i_trumb'];
	
	$StartX_Width  = $_POST['w'] - $_POST['x'];
	$StartY_Height = $_POST['h'] - $_POST['y'];
	try
	{
		if($_POST["Process"] == "rotate")
		{
			$ok = false;
			$Path = str_replace("//", "/", ROOT_DIR.DIRSEP.$_POST["PathImage"]);
			$imgPath = explode("?", $Path);
			if(is_array($imgPath)) {
				$imgPathReal = $imgPath[0];
				$ok = rotateImage($imgPathReal, $_POST["TypeRotate"]);
			}
			if($ok) {
				$json_export["ok"] = "Успешно!";
			}
			else {
				throw new Exception("Ошибка при обработке изображения!");
			}
		}
		/* Кроп изображения */
		else
		{		
			/* 
			 * Если есть Image Magick 
			 */
			if(class_exists("Imagick"))
			{		
				$picture = new Imagick($ImageOriginal);
				$picture->setCompressionQuality(90);
				$picture->setImageFormat("jpeg");
				$picture->cropImage($StartX_Width, $StartY_Height, $_POST['x'], $_POST['y']);
				$picture->resizeImage($_POST['ww_t'], $_POST['hh_t'], Imagick::FILTER_LANCZOS, 1);		
				$picture->writeImage($ImageTrumbnail);		
				$picture->clear();
				$picture->destroy();
			}
			
			/*
			 * Если нет, то обрабатываем стандартными средствами :-) 
			 */
			else
			{
				$img_r = imagecreatefromjpeg($ImageOriginal);
				$dst_r = imagecreatetruecolor($_POST['ww_t'], $_POST['hh_t']);
				imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['x'], $_POST['y'], $_POST['ww_t'], $_POST['hh_t'], $StartX_Width, $StartY_Height);
				imagejpeg($dst_r, $ImageTrumbnail, 90);	
			}		
			
			$file_exists = file_exists($ImageTrumbnail);
			if(!$file_exists) {
				throw new Exception("Could not open the file!");
			}
			else
			{
				$json_export["success"]["trumb"] = $_POST['i_trumb'];
				$json_export["success"]["new_width"] = $_POST["ww_t"];
				$json_export["success"]["number"] = $_POST["num"];
				$json_export["success"]["prefix"] = $_POST["prefixx"];	
			}
		}
	}
	catch(Exception $e) {
		$json_export["err"] = "Error (File: ".$e->getFile().", line ".$e->getLine()."): ".$e->getMessage();	
	}
	
	exit(getJSON($json_export));	
}

?>